//
//  DrawingBoardView.m
//  TestPrj
//
//  Created by 朱铅峰 on 2019/11/1.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "DrawingBoardView.h"

@interface DrawingBoardView()

@property(nonatomic,strong) NSMutableArray<DrawingBezierPath *> *paths;

@end

@implementation DrawingBoardView

- (UIColor *)lineColor {
    
    if (!_lineColor) {
        return [UIColor redColor];
    }
    return _lineColor;
}

- (CGFloat)lineWidth {
    
    if (_lineWidth == 0) {
        return 5;
    }
    return _lineWidth;
}

- (NSArray *)paths{
    
    if(!_paths){
        _paths=[NSMutableArray array];
    }
    return _paths;
}

- (void)clear {
    
    [self.paths removeAllObjects];
    
    [self setNeedsDisplay];
}

//回退
- (void)undo {
    
    [self.paths removeLastObject];
    
    //重绘
    [self setNeedsDisplay];
}

//橡皮擦
- (void)eraser {
    
    _lineColor = self.backgroundColor;
}

//获取截图
- (UIImage *)capture {
    
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 1.0);
    
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    // 获取触摸对象
    UITouch *touch = [touches anyObject];
    
    // 获取手指的位置
    CGPoint point = [touch locationInView:touch.view];
    
    //当手指按下的时候就创建一条路径
    DrawingBezierPath *path = [DrawingBezierPath bezierPath];
    
    //设置画笔宽度
    [path setLineWidth:self.lineWidth];
    
    //设置画笔颜色
    [path setLineColor:[self lineColor]];
    
    //设置起点
    [path moveToPoint:point];
    
    // 把每一次新创建的路径 添加到数组当中
    [self.paths addObject:path];
    
    //回调
    if (self.drawPathChangeAction) {
        self.drawPathChangeAction([self.paths lastObject]);
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    // 获取触摸对象
    UITouch *touch=[touches anyObject];
    
    // 获取手指的位置
    CGPoint point = [touch locationInView:touch.view];
    
    // 连线的点
    [[self.paths lastObject] addLineToPoint:point];
    
    // 重绘
    [self setNeedsDisplay];
    
    //回调
    if (self.drawPathChangeAction) {
        self.drawPathChangeAction([self.paths lastObject]);
    }
}

- (void)drawRect:(CGRect)rect {
    
    for (DrawingBezierPath *path in self.paths) {
        
        //设置颜色
        [path.lineColor set];
        
        // 设置连接处的样式
        [path setLineJoinStyle:kCGLineJoinRound];
        
        // 设置头尾的样式
        [path setLineCapStyle:kCGLineCapRound];
        
        //渲染
        [path stroke];
    }
}

@end


#pragma mark -

@implementation DrawingBezierPath



@end
